<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { IconPlay, IconAdd, IconHeart } from "@/components/icons";
import Navbar from "@/components/Navbar.vue";
import ArtistApplicationDialog from "@/components/ArtistApplicationDialog.vue";
import { usePlaylistAPI } from "@/services/playlist";
import { useUserStore } from "@/stores/user";
import { usePlaylistStore } from "@/stores/playlist";
const userStore = useUserStore();
const playlistStore = usePlaylistStore();

const userInfo = computed(() => ({
  nickname: userStore.username,
  avatar: userStore.avatarUrl || userStore.defaultAvatarUrl,
  followingArtists: 0, // 这个值需要从后端获取
  musicRecords: 0, // 这个值需要从后端获取
  joinDate: "2025年6月3日", // 这个日期可能需要从后端获取或格式化 birthday
  signature: userStore.description || "这个人很懒，什么都没写~",
  favoriteSongs: [
    {
      id: 1,
      title: "风继续吹",
      cover:
        "https://xirealm.oss-cn-beijing.aliyuncs.com/xi/20250529150705.png",
      plays: 10000,
      favorites: 2000,
      artist: "张国荣",
    },
  ],
}));

const userType = computed(() => {
  switch (userStore.isSinger) {
    case 1:
      return { text: "音乐人", class: "bg-[#d92323]/20 text-[#d92323]" };
    case -1:
      return {
        text: "音乐人审核中",
        class: "bg-yellow-500/20 text-yellow-600",
      };
    default:
      return { text: "普通用户", class: "bg-white/20 text-white" };
  }
});

const { getUserPlaylists, getFavoritePlaylist } = usePlaylistAPI();

const navItems = [
  { id: "created", name: "我的歌单" },
  { id: "favorite", name: "收藏歌单" },
  { id: "songs", name: "收藏音乐" },
];
const currentTab = ref(navItems[0]);

// 获取用户创建的歌单
const fetchUserPlaylists = async () => {
  try {
    const response = await getUserPlaylists(userStore.uid);
    const playlists = response.map((playlist: any) => ({
      id: playlist.id,
      name: playlist.name,
      cover:
        playlist.cover ||
        "https://xirealm.oss-cn-beijing.aliyuncs.com/xi/20250528224042.png",
      songCount: playlist.musicIds?.length || 0,
    }));
    playlistStore.setUserPlaylists(playlists);
  } catch (error) {
    console.error("获取用户歌单失败:", error);
  }
};

// 获取收藏的歌单
const fetchFavoritePlaylists = async () => {
  try {
    const response = await getFavoritePlaylist(userStore.uid);
    const playlists = response
      .filter((playlist: any) => playlist !== null)
      .map((playlist: any) => ({
        id: playlist.id,
        name: playlist.name,
        cover:
          playlist.cover ||
          "https://xirealm.oss-cn-beijing.aliyuncs.com/xi/20250528224042.png",
        songCount: playlist.musicIds?.length || 0,
        category: playlist.category || "未分类",
        description: playlist.description,
      }));
    playlistStore.setFavoritePlaylists(playlists);
  } catch (error) {
    console.error("获取收藏歌单失败:", error);
  }
};

const createdPlaylists = computed(() => playlistStore.userPlaylists);
const favoritePlaylists = computed(() => playlistStore.favoritePlaylists);

onMounted(() => {
  fetchUserPlaylists();
  fetchFavoritePlaylists();
});

// 跳转到歌单详情页
const router = useRouter();
const goToPlaylist = (playlistId: string) => {
  router.push(`/playlist/${playlistId}`);
};

// 添加弹窗控制
const showArtistModal = ref(false);
</script>

<template>
  <div class="min-h-screen bg-[#f5f5f5]">
    <!-- 背景图片 -->
    <div class="relative h-40 overflow-hidden">
      <div
        class="absolute inset-0 bg-cover bg-center bg-[url('@/assets/images/bg_profile.jpg')] scale-110"
      ></div>
      <div
        class="absolute inset-0 bg-gradient-to-b from-black/60 to-black/40"
      ></div>
    </div>

    <!-- 添加版心容器 -->
    <div class="max-w-7xl mx-auto">
      <!-- 主要内容区域 -->
      <div class="relative -mt-40 px-8 pb-8">
        <!-- 头部个人信息 -->
        <div class="flex gap-8 mb-10">
          <div class="shrink-0 relative translate-y-12">
            <img
              :src="userInfo.avatar"
              alt="用户头像"
              class="w-48 h-48 rounded-full object-cover"
            />
          </div>
          <div class="flex-1 text-white pt-12">
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-4">
                <h1 class="text-3xl font-bold">{{ userInfo.nickname }}</h1>
                <span
                  class="px-3 py-1 text-sm rounded-full"
                  :class="userType.class"
                  >{{ userType.text }}</span
                >
              </div>
              <button
                @click="showArtistModal = true"
                class="px-4 py-2 text-white rounded-sm transition"
                :class="
                  userStore.isSinger === -1
                    ? 'bg-gray-400 cursor-not-allowed'
                    : 'bg-[#d92323] hover:bg-[#d93333]'
                "
                :disabled="userStore.isSinger === -1"
              >
                {{ userStore.isSinger === -1 ? "认证审核中" : "认证音乐人" }}
              </button>
            </div>
            <p class="text-sm text-white/80 mt-2">
              音乐记录始于 {{ userInfo.joinDate }}
            </p>
            <p class="mt-4 text-white/90">{{ userInfo.signature }}</p>
            <div class="mt-4 flex items-center gap-8">
              <div class="flex flex-col items-start">
                <span class="text-sm text-gray-600">关注音乐人</span>
                <span class="text-xl font-bold text-black">
                  {{ userInfo.followingArtists }}
                </span>
              </div>
              <div class="flex flex-col items-start">
                <span class="text-sm text-gray-600">音乐记录</span>
                <span class="text-xl font-bold text-black">
                  {{ userInfo.musicRecords }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 内容区域背景 -->
        <div class="pt-6 px-8">
          <!-- 导航栏 -->
          <Navbar v-model="currentTab" :items="navItems" class="mb-6" />

          <!-- 创建的歌单 -->
          <div v-if="currentTab.id === 'created'" class="mt-8">
            <h2 class="text-xl font-bold mb-6">创建的歌单</h2>
            <div class="grid grid-cols-5 gap-4">
              <div
                v-for="playlist in createdPlaylists"
                :key="playlist.id"
                class="flex flex-col group hover:bg-white hover:shadow-md rounded-lg transition duration-300 p-3 cursor-pointer"
                @click="goToPlaylist(playlist.id)"
              >
                <div class="relative">
                  <img
                    :src="playlist.cover"
                    :alt="playlist.name"
                    class="w-full aspect-square object-cover rounded-lg mb-2"
                  />
                </div>
                <h3 class="font-medium text-gray-900 line-clamp-1">
                  {{ playlist.name }}
                </h3>
              </div>
            </div>
          </div>

          <!-- 收藏的歌单 -->
          <div v-if="currentTab.id === 'favorite'" class="mt-8">
            <h2 class="text-xl font-bold mb-6">收藏的歌单</h2>
            <div class="grid grid-cols-5 gap-4">
              <div
                v-for="playlist in favoritePlaylists"
                :key="playlist.id"
                class="flex flex-col group hover:bg-white hover:shadow-md rounded-lg transition duration-300 p-3 cursor-pointer"
                @click="goToPlaylist(playlist.id)"
              >
                <div class="relative">
                  <img
                    :src="playlist.cover"
                    :alt="playlist.name"
                    class="w-full aspect-square object-cover rounded-lg mb-2"
                  />
                </div>
                <h3 class="font-medium text-gray-900 line-clamp-1">
                  {{ playlist.name }}
                </h3>
                <p class="text-sm text-gray-500 line-clamp-2 mt-1">
                  {{ playlist.description }}
                </p>
              </div>
            </div>
          </div>

          <!-- 收藏的歌曲 -->
          <div v-if="currentTab.id === 'songs'" class="mt-8">
            <h2 class="text-xl font-bold mb-6">收藏的歌曲</h2>
            <div class="space-y-4">
              <div
                v-for="song in userInfo.favoriteSongs"
                :key="song.id"
                class="flex items-center gap-4 p-3 hover:bg-gray-50 rounded-lg group"
              >
                <div
                  class="w-8 flex justify-center text-gray-400 group-hover:text-[#ec4141]"
                >
                  <IconPlay class="w-5 h-5" />
                </div>
                <img
                  :src="song.cover"
                  :alt="song.title"
                  class="w-12 h-12 object-cover rounded"
                />
                <div class="flex-1">
                  <h3 class="font-bold text-gray-900">{{ song.title }}</h3>
                  <p class="text-sm text-gray-500">{{ song.artist }}</p>
                </div>
                <button
                  class="flex items-center gap-2 text-gray-500 hover:text-[#ec4141]"
                >
                  <IconHeart class="w-5 h-5" />
                  <span>{{ song.favorites }}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 音乐人申请弹窗 -->
    <ArtistApplicationDialog v-model:visible="showArtistModal" />
  </div>
</template>
